/**
 *
 */
package de.sendorian.app.forumArchive.download;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.annotation.Nonnull;

import org.apache.log4j.Logger;

import de.sendorian.app.forumArchive.domain.Archive;
import de.sendorian.app.forumArchive.domain.Topic;

class ArchiveDownloaderTask implements Runnable {
	private static final Logger logger = Logger.getLogger(ArchiveDownloaderTask.class);

	Archive archive;
	Topic topic;
	Set<String> downloadedFiles;
	List<String> filesInArchives;

	ArchiveDownloaderTask(@Nonnull Archive archive, @Nonnull final Topic topic,
	    @Nonnull Set<String> downloadedFiles, @Nonnull List<String> filesInArchives) {
		this.archive = archive;
		this.topic = topic;
		this.downloadedFiles = downloadedFiles;
		this.filesInArchives = filesInArchives;
	}


	public void run() {
		try {
			logger.info("Downloading " + archive.getName() + " from topic \"" + topic.getName()
			    + "\"");
			boolean downloaded = archive.save();
			downloadedFiles.add(archive.getName());
			if (downloaded) {
				filesInArchives.addAll(archive.deflate());
				archive.delete();
				logger.info("Downloaded and deflated " + archive.getName() + " from topic \""
				    + topic.getName() + "\"");
			}
		} catch (IOException e) {
			logger.error("Could not save or deflate archive \"" + archive.getUrl()
			    + "\" in topic  \"" + topic.getName() + "\" (" + topic.getUrl() + ")", e);
		}
	}
}